package com.shengsiyuan.nio;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

public class NioTestDecodeEncode {

    public static void main(String[] arg) throws Exception {

        String inputFile = "C:\\Users\\Administrator\\IdeaProjects\\Netty-Learning\\src\\main\\java\\com\\shengsiyuan\\nio\\text\\NioTest_in.txt";
        String outputFile = "C:\\Users\\Administrator\\IdeaProjects\\Netty-Learning\\src\\main\\java\\com\\shengsiyuan\\nio\\text\\NioTest_out.txt";

        RandomAccessFile inputAccessFile = new RandomAccessFile(inputFile, "r");
        RandomAccessFile outputAccessFile = new RandomAccessFile(outputFile, "rw");

        long inputLength = new File(inputFile).length();

        FileChannel inputChannel = inputAccessFile.getChannel();
        FileChannel outputChannel = outputAccessFile.getChannel();

        MappedByteBuffer inputData = inputChannel.map(FileChannel.MapMode.READ_ONLY, 0, inputLength);

        System.out.println("==============");

        Charset.availableCharsets().forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });

        System.out.println("==============");

        //Charset charset = Charset.forName("iso-8859-1");
        Charset charset = Charset.forName("utf-8");// 字符集对象，代表着一种编码
        CharsetDecoder charsetDecoder = charset.newDecoder();// 解码器，字节数组变成字符串
        CharsetEncoder charsetEncoder = charset.newEncoder();// 编码器，字符串变成字节数组

        CharBuffer charBuffer = charsetDecoder.decode(inputData);// 解码
        ByteBuffer outputData = charsetEncoder.encode(charBuffer);// 编码

        outputChannel.write(outputData);

        inputAccessFile.close();
        outputAccessFile.close();



        /**
         * 文件在磁盘上的保存时方式都是字节
         *
         * 字符是对字节的一种编码方式，一种表示方式
         *
         * 存储在磁盘上的文件都会有一种编码
         *
         * ---------------------------------------------------
         *
         *
         */
    }
}
